package com.ly.mpayment.persist.service.zero;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.DownRechargeFlow;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.hibernate.Page;
import com.ly.mpayment.persist.service.downrechargeflow.DownRechargeFlowServiceImpl;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.ftp.Ftp;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.ly.mpayment.persist.entity.DownShopInfo;
import com.ly.mpayment.persist.entity.ZeroBalance;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;

@Service
@Component("autoZeroBalanceService")
public class AutoZeroBalanceService {

	Logger logger = Logger.getLogger(AutoZeroBalanceService.class);

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	ZeroBalanceService zeroBalanceService;

	@Autowired
	IUpShopInfoService iUpShopInfoService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IUpShopInfoService upShopInfoService;

	@Autowired
	ZeroBalanceUpService zeroBalanceUpService;

	/**
	 * 0点余额
	 */
	public void zeroBalance() {
		List<DownShopInfo> list = shopService.findShopList(new HashMap());
		if(list != null) {
			for(DownShopInfo downShopInfo : list) {
				ZeroBalance zero = new ZeroBalance();
				zero.setBalance(downShopInfo.getDownshopbalance());
				zero.setCreateTime(DateUtils.getNowDate());
				zero.setUser(downShopInfo.getUser());
				zeroBalanceService.saveZeroBalance(zero);
			}
		}
		//政邦对账单
		logger.info("零点余额:....");
		zhengBangBill();
	}

	/**
	 * 查询政邦成功的前一日的订单 生成明细txt文件
	 *  ##政邦流水|充值号码|金额|充值日期|成功编码|结果编码
	 *  20211206132651674PNXL2TZOWRMLH|13513718520|50|2021-12-06 13:26:52|2|100101101022112061327023161881
	 */
	private void zhengBangBill(){
		File files = new File("/zhengbang/wwwroot/"+DateUtils.toShortDate(DateUtils.addDays(DateUtils.getNowDate(),-1)).replaceAll("-","")+".txt");
		logger.info("生成对账单:"+files.getAbsolutePath());
		if(files.exists()){
			try {
				files.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Map<String, Object> parameters = MapUtil.getMap();
		parameters.put(":useruuid", "2c922ab97d30cc8c017d55eaa6d300c0");
		parameters.put(":status", 2);
		parameters.put(":createtime",DateUtils.toShortDate(DateUtils.addDays(DateUtils.getNowDate(),-1))+" 00:00:00");
		parameters.put(":endtime", DateUtils.toShortDate(DateUtils.addDays(DateUtils.getNowDate(),-1))+" 23:59:59");

		List<String> messageList = new ArrayList<>();
		DownRechargeFlowServiceImpl serviceImpl = (DownRechargeFlowServiceImpl) flowService;
		// 声明一个工作薄
		try {
			int start = 0 ;
			int pageSize = Integer.valueOf(CookieRedis.get("exportPageSize"));
			Page page = new Page();
			long totalCount =  serviceImpl.findCountResult(ExportExcelUtil.getFlowOrderSqlDownCount(parameters) , MapUtil.getMap());

			parameters = MapUtil.getMap();
			parameters.put(":useruuid", "2c922ab97d30cc8c017d55eaa6d300c0");
			parameters.put(":status", 2);
			parameters.put(":createtime",DateUtils.toShortDate(DateUtils.addDays(DateUtils.getNowDate(),-1))+" 00:00:00");
			parameters.put(":endtime", DateUtils.toShortDate(DateUtils.addDays(DateUtils.getNowDate(),-1))+" 23:59:59");

			page.setPageSize(totalCount > pageSize ? pageSize : (int)totalCount);
			int count = (int) (totalCount / pageSize) <= 0 ? 1 : (int) (totalCount / pageSize) + 1;
			for(int j = 0 ; j < count ; j++){
				start = start+1;
				page.setStart(start);
				List<DownRechargeFlow> orders = PaginationUtil.queryPaginationNotCount(ExportExcelUtil.getFlowOrderSql(parameters), page, serviceImpl.getSessionFactory().openSession()).getResult();
				//插入需导出的数据
				for(int i= 0;i < orders.size();i++){
					//政邦流水|充值号码|金额|充值日期|成功编码|结果编码
					StringBuilder stringBuilder = new StringBuilder();

					DownRechargeFlow flow = orders.get(i);
					stringBuilder.append(flow.getDownreqid());
					stringBuilder.append("|");
					stringBuilder.append(flow.getDowonphonenum());
					stringBuilder.append("|");
					stringBuilder.append(flow.getRechargeamount() == null ? "" :  flow.getRechargeamount()+"");
					stringBuilder.append("|");
					stringBuilder.append(DateUtils.toLongDate(flow.getCreatetime()));
					stringBuilder.append("|");
					stringBuilder.append(flow.getStatus());
					stringBuilder.append("|");
					stringBuilder.append(flow.getRemark());
					messageList.add(stringBuilder.toString());
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		try {
			writeToTxt(messageList,files);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 方法写入txt
	 *
	 * @param messageList
	 * @throws FileNotFoundException
	 */
	public void writeToTxt(List<String> messageList, File files) throws FileNotFoundException {
		FileOutputStream fos = new FileOutputStream(files.getAbsolutePath());
		// 逐行写入
		PrintWriter pw = new PrintWriter(fos);
		for (String message : messageList) {
			pw.println(message);
		}
		pw.close();

	}

	/**
	     *  每天凌晨1点上传前一天的日志
	 */
	public void uploadLogFtp() {

		Ftp ftp = new Ftp("101.204.228.65",21,"hunanrenxhf_p","hunanrenxhf_p30842");
		//进入远程目录
		ftp.cd("/");
		String path = System.getProperty("catalina.home");
		LocalDate yesterday = LocalDate.now().plusDays(-1);
        DateTimeFormatter sf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //String fileName = path + "/logs/ele.log." + yesterday.format(sf) ;
        String fileName = "/opt/data/apache-tomcat-8.0.26/logs/ele.log.2020-11-15";
		logger.info("是否是文件:"+FileUtil.isFile(fileName));
		//上传本地文件
		if(ftp.upload("/home", FileUtil.file(fileName))) {
			logger.info("文件上传成功:"+fileName);
		} else {
			logger.info("文件上传失败:"+fileName);
		}

		//下载远程文件
		//ftp.download("/opt/upload", "test.jpg", FileUtil.file("e:/test2.jpg"));

		//关闭连接
		try {
			ftp.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 1小时查询一次账单 对比余额
	 */
	public void autoQueryBalance(){
//		List<UpShopInfo> shopInfos = iUpShopInfoService.findAllByProvince();
//		if(shopInfos != null ){
//			shopInfos.forEach(upShopInfo -> {
//				if(!StringUtils.isBlank(upShopInfo.getQueryBalanceAddress())){
//					switch (upShopInfo.getShopnum()){
//						case Config.youxinya:
//							break;
//						case Config.wanhuichong:
//							break;
//						case Config.dianxinwangting:
//							break;
//						case Config.sanchongmao:
//							break;
//						case Config.luhongwangluo:
//							break;
//						case Config.zhengheng:
//							break;
//						case Config.chuzhouxiaoling:
//							break;
//						case Config.zhengchuang:
//							break;
//						case Config.zhengchuang2:
//							break;
//						default:
////				flowService.orderHanlderFailt(order, this, flowService, shopService, taskExecutor, "上游配置错误");
////				flowService.orderHanlder(order, this, flowService, shopService, taskExecutor, "success");
//							logger.info("default:"+upShopInfo.getShopnum());
//							break;
//					}
//				}
//			});
//		}
	}


}
